import { getUserByIdApi, getUserInfoApi, loginApi } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
// 获取token
  setToken(state, data) {
    setToken(data)
    state.token = data
  },
  // 获取用户详情
  setUserInfo(state, data) {
    state.userInfo = data
  },
  // 删除token
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  // 删除用户数据
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 登录
  async login(store, data) {
    const res = await loginApi(data)
    console.log(res)
    // store.commit('setToken', res.data.data)
    // 响应拦截器结构过了，不用再取子属性
    store.commit('setToken', res)
    // loginApi(data).then(res => {
    //   console.log(res)
    //   state.commit('setToken', res.data.data)
    // })
    localStorage.setItem('loginTime', Date.now())
  },
  // 用户
  async getUserInfo(store) {
    const res = await getUserInfoApi()
    const detail = await getUserByIdApi(res.userId)
    console.log('用户详情', res)
    console.log('用户基本信息', detail)
    store.commit('setUserInfo', {
      ...res,
      ...detail
    })
  },
  // 退出登录
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
